import ctypes
import sys
import customtkinter as ctk
from utils.utils import logger, clean_old_mei_tempdirs, get_current_version
from config.version_checker import get_remote_version, show_update_dialog
from update.update_manager import perform_update_flow


def check_and_update_on_startup() -> bool:
    try:
        current_ver = get_current_version()
        remote_ver, download_url, changelog, exe_sha256, remote_arch = get_remote_version()
        if not all([remote_ver, download_url, exe_sha256, remote_arch]):
            logger.warning("远程版本信息不完整，跳过更新")
            return True
        from pkg_resources import parse_version
        if parse_version(remote_ver) > parse_version(current_ver):
            should_update = show_update_dialog(current_ver, remote_ver, changelog)
            if should_update:
                perform_update_flow(current_ver, remote_ver, download_url, changelog, exe_sha256, remote_arch)
                return False
        return True
    except Exception as e:
        logger.error(f"启动更新检查异常: {e}", exc_info=True)
        return True


'''def run_main_gui():
    clean_old_mei_tempdirs()
    app = ctk.CTk()
    app.title("电商数据采集工具")
    app.geometry("600x400")
    app.resizable(False, False)
    ctk.CTkLabel(app, text="电商数据采集工具", font=("Microsoft YaHei", 20, "bold")).pack(pady=25)
    ctk.CTkLabel(app, text=f"当前版本：{get_current_version()}").pack()
    status_label = ctk.CTkLabel(app, text="状态：就绪", text_color="green")
    status_label.pack(pady=15)

    def start_crawling():
        status_label.configure(text="状态：爬取中...", text_color="blue")
        status_label.after(2000, lambda: status_label.configure(text="状态：完成", text_color="green"))
    ctk.CTkButton(app, text="开始采集", command=start_crawling, width=150, height=40).pack(pady=20)

    def on_close():
        clean_old_mei_tempdirs()
        app.destroy()
    app.protocol("WM_DELETE_WINDOW", on_close)
    app.mainloop()
'''

if __name__ == '__main__':
    try:
        ctypes.windll.shcore.SetProcessDpiAwareness(1)
    except:
        pass
    ctk.set_appearance_mode("system")
    ctk.set_default_color_theme("blue")
    logger.info("========== 程序启动 ==========")
    # 检查更新
    if not check_and_update_on_startup():
        logger.info("更新流程已接管，主程序无需启动")
        exit(0)
    # 导入并启动登录窗口
    from view.login_window import LoginWindow
    login_app = LoginWindow()
    login_app.mainloop()

    logger.info("========== 程序结束 ==========")